package com.jinlejia.erp.ui.house;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jinlejia.erp.R;
import com.jinlejia.erp.adapter.SearchDistrictAdapter;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.bean.EstateBean;
import com.jinlejia.erp.bean.InterestCommunityBean;
import com.jinlejia.erp.common.RecycleViewDivider;
import com.jinlejia.erp.databinding.ActivityHasSelectDistrictBinding;
import com.jinlejia.erp.ui.common.ProgressDialog;
import com.jinlejia.erp.utils.DataFilter;
import com.weight.CustomToast;
import com.zhy.http.okhttp.OkHttpUtils;

import org.simple.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;

/**
 * 已选小区
 */
public class HasSelectDistrictActivity extends AppCompatActivity {

    SearchDistrictAdapter adapter;
    JSONArray jsonArray = new JSONArray();
    private String csCode;
    ProgressDialog progressDialog;
    private HashSet<String> select = new HashSet<>();
    private ActivityHasSelectDistrictBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_has_select_district);

        binding.btBack.setOnClickListener(this::onClick);
        binding.btSubmit.setOnClickListener(this::onClick);
        csCode = getIntent().getStringExtra("csCode");
        ArrayList<InterestCommunityBean> list = (ArrayList) getIntent().getSerializableExtra("list");
        ArrayList<EstateBean> list1 = new ArrayList<>();
        for (InterestCommunityBean interestCommunityBean:list) {
            EstateBean estateBean = new EstateBean();
            estateBean.setEstateName(interestCommunityBean.getEstate());
            estateBean.setArea(interestCommunityBean.getArea());
            estateBean.setCounty(interestCommunityBean.getCounty());
            list1.add(estateBean);
        }
        select = new HashSet<>(getIntent().getStringArrayListExtra("select"));
        binding.yfrvList.setHasFixedSize(true);
        binding.yfrvList.setLayoutManager(new LinearLayoutManager(this));
        binding.yfrvList.addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.VERTICAL, 2, getResources().getColor(R.color.colorDivider)));
        adapter = new SearchDistrictAdapter(list1,"","CHECK");
        binding.yfrvList.setAdapter(adapter);
        adapter.setSelectList(select);
        progressDialog = new ProgressDialog(this,"请稍后...");
        adapter.setOnSelectedListiner(icb -> {
            if( !select.contains(icb.getEstateName()) ){
                select.add(icb.getEstateName());
            }
        });
        adapter.setOnRemoveListiner(icb -> select.remove(icb.getEstateName()));
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_back:
                finish();
                break;
            case R.id.bt_submit:
                jsonArray = new JSONArray();
                if( select.size()>0 ) {
                    if(TextUtils.isEmpty(csCode)){
                        ArrayList dataList = new ArrayList();
                        for(int i=0;i<adapter.getData().size();i++){
                            if( select.contains( ((EstateBean)adapter.getData().get(i)).getEstateName() ) ){
                                dataList.add(adapter.getData().get(i));
                            }
                        }
                        EventBus.getDefault().post(dataList,"TAG_INTEREST_DISTRICT");
                        //TODO 注意
//                        AppManger.getAppManager().finishActivity(SearchDistrictActivity.class);
                        finish();
                    }else {
                        for (String name : select) {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("csCode", csCode);
                            jsonObject.put("estateName", name);
                            jsonArray.add(jsonObject);
                        }
                        save();
                    }
                }else{
                    CustomToast.showToast(HasSelectDistrictActivity.this,"请选择小区",1500);
                }

                break;
        }
    }

    private void save(){
        String url;
        if( getIntent().getStringExtra("type").equals("shs") ){
            url = ApiConfig.SAVE_SHS_ENJOY_ESTATE;
        }else{
            url = ApiConfig.SAVE_RENT_ENJOY_ESTATE;
        }
        progressDialog.show();
        OkHttpUtils.postString()
                .url(url)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonArray.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (DataFilter.filter(HasSelectDistrictActivity.this, response)) {
                            CustomToast.showToast(HasSelectDistrictActivity.this,"提交成功",1500);
                            finish();
                        }
                    }
                });
    }

    @Override
    protected void onDestroy() {
        if (null != progressDialog && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        super.onDestroy();
    }
}
